package com.spzx.user.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.user.domain.Region;
import com.spzx.user.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spzx.user.mapper.UserAddressMapper;
import com.spzx.user.domain.UserAddress;
import com.spzx.user.service.IUserAddressService;

/**
 * 用户地址Service业务层处理
 *
 * @author atguigu
 * @date 2024-06-29
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService {

    @Autowired
    private IRegionService regionService;

    @Override
    public List<UserAddress> selectUserAddressList() {
        Long userId = SecurityUtils.getUserId();
        return this.lambdaQuery().eq(UserAddress::getUserId, userId).list();
    }

    @Override
    public void insertUserAddress(UserAddress userAddress) {
        Long userId = SecurityUtils.getUserId();
        userAddress.setUserId(userId);
        String fullAddress = regionService.getFullAddress(userAddress.getDistrictCode(), userAddress.getAddress());
        userAddress.setFullAddress(fullAddress);
        // 如果指定新增的地址为默认地址，则需要将该用户其他的地址修改为非默认
        if (userAddress.getIsDefault() == 1) {
            this.lambdaUpdate().eq(UserAddress::getUserId, userId).set(UserAddress::getIsDefault, 0).update();
        }
        this.save(userAddress);
    }

    @Override
    public void updateUserAddress(UserAddress userAddress) {
        String fullAddress = regionService.getFullAddress(userAddress.getDistrictCode(), userAddress.getAddress());
        userAddress.setFullAddress(fullAddress);
        // 一个用户最多只能有一个默认地址
        if (userAddress.getIsDefault() == 1) {
            this.lambdaUpdate()
                    .eq(UserAddress::getUserId, userAddress.getUserId())
                    .set(UserAddress::getIsDefault, 0).update();
        }
        this.updateById(userAddress);
    }
}
